package ldh.im.fxbase.util;

import java.lang.reflect.Constructor;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class BeanFactory {

    private static BeanFactory instance = null;

    private Map<Class, Object> beanMap = new ConcurrentHashMap();

    private BeanFactory() {

    }

    public static BeanFactory getInstance() {
        if(instance == null) {
            synchronized (BeanFactory.class) {
                if (instance == null) {
                    instance = new BeanFactory();
                }
            }
        }
        return instance;
    }

    public <T> T getBean(Class<T> tClass) {
        if (beanMap.containsKey(tClass)) {
            return (T) beanMap.get(tClass);
        }
        T t = newClass(tClass);
        beanMap.putIfAbsent(tClass, t);
        return (T) beanMap.get(tClass);
    }

    private <T>T newClass(Class<T> tClass) {
        try {
            Constructor<T> constructor = tClass.getConstructor();
            return constructor.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("实例化" + tClass.getName() + "失败", e);
        }

    }
}
